<template>
  <div class="safety-wrap">
    <el-form class="form">
      <!-- <el-form-item label-width="100px" label="用户ID：">
        <el-input :model="userId" type="text"/>
      </el-form-item>
      <el-form-item label-width="100px">
        <el-button type="primary" icon="el-icon-search">搜索</el-button>
      </el-form-item> -->
      <el-form-item label-width="100px">
        <el-button type="primary" @click="handleAdd">+添加</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="index" label="序号" width="180"/>
      <el-table-column prop="nickname" label="昵称" width="200"/>
      <el-table-column prop="userid" label="ID" width="200"/>
      <el-table-column prop="phone" label="手机号" width="200"/>
      <!-- <el-table-column prop="createTime" sortable label="创建时间" width="200"/> -->
      <el-table-column label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button type="danger" @click="handleDelete(scope)">删除</el-button>
          <el-button type="primary" @click="handleModification(scope)">修改</el-button>
          <!-- <el-button type="primary" @click="handleDetail(scope)">查看详情</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>10" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog
      :visible.sync="centerDialogVisible"
      title="提示"
      width="30%"
      center>
      <span>确认删除？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDeleteConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="changeDialogVisible"
      :title="title"
      width="30%"
      center>
      <el-form ref="form" :model="form" :rules="formRules">
        <el-form-item prop="username" label-width="150px" label="用户名：">
          <el-input v-model="form.username" name="username" type="text" auto-complete="on" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="username" label-width="150px" label="昵称：">
          <el-input v-model="form.nickname" name="username" type="text" auto-complete="on" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item prop="phone" label-width="150px" label="手机号码：">
          <el-input v-model="form.phone" name="username" type="text" auto-complete="on" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item prop="password" label-width="150px" label="密码：">
          <el-input v-model="form.password" name="username" type="text" auto-complete="on" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item prop="againPassword" label-width="150px" label="再一次输入密码：">
          <el-input v-model="form.againPassword" name="username" type="text" auto-complete="on" placeholder="请再一次输入密码" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { isvalidUsername, validatePhone } from '@/utils/validate'
import { system, systemDelete, systemAdd, systemUpdate } from '@/api/user'
export default {
  name: 'Publish',
  components: {
    Pagination
  },
  data() {
    let passFlag = null
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        passFlag = value
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!validatePhone(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    const vaidateAgain = (rule, value, callback) => {
      if (typeof passFlag !== 'string') {
        callback(new Error('两次密码不一致'))
        return false
      }
      if (passFlag.trim() !== value) {
        callback(new Error('两次密码不一致'))
        return false
      }
      callback()
    }
    return {
      id: '',
      userid: '',
      total: 0,
      flag: true,
      title: '添加后台管理用户',
      listQuery: {
        page: 1,
        limit: 10
      },
      centerDialogVisible: false,
      changeDialogVisible: false,
      formRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }],
        againPassword: [{ required: true, trigger: 'blur', validator: vaidateAgain }],
        phone: [{ required: true, trigger: 'blur', validator: validateMobile }],
        nickname: [{ required: true, trigger: 'blur', validator: validateUsername }]
      },
      form: {
        username: '',
        password: '',
        phone: '',
        nickname: '',
        againPassword: ''
      },
      iDisplayStart: 0,
      iDisplayLength: 10,
      list: []
    }
  },
  computed: {
    tableData() {
      const result = []
      this.list.map((item, index) => {
        item = Object.assign({}, item, { index: `${(this.listQuery.page - 1) * this.listQuery.limit + 1 + index}` })
        result.push(item)
      })
      return result
    }
  },
  created() {
    this.getUserMessage()
  },
  methods: {
    handleDelete(scope) {
      this.centerDialogVisible = true
      this.id = scope.row.userid
    },
    handleDeleteConfirm() {
      const userid = this.id
      systemDelete({ userid })
        .then((res) => {
          this.$message.success({
            message: '删除成功',
            duration: 1000
          })
          this.getUserMessage()
        }).catch((res) => {
          this.$message.error({
            message: '请稍后再试',
            duration: 1000
          })
        })
    },
    handleModification(scope) {
      this.userid = scope.row.userid
      this.form.username = scope.row.username
      this.form.nickname = scope.row.nickname
      this.form.phone = scope.row.phone
      this.flag = false
      this.title = '修改用户信息'
      this.changeDialogVisible = true
    },
    getList(prop) {
      this.listQuery.page = prop.page
      this.listQuery.limit = prop.limit
      this.iDisplayStart = (prop.page - 1) * prop.limit
      this.iDisplayLength = prop.limit
      this.getUserMessage()
    },
    getUserMessage() {
      const { iDisplayStart, iDisplayLength } = this
      system({ iDisplayStart, iDisplayLength })
        .then((res) => {
          const data = res.data
          this.total = res.total
          this.list = data
        }).catch((e) => {
          this.$message.error({
            message: '请稍后再试',
            duration: 1000
          })
        })
    },
    handleAddUser() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.flag) {
            const { username, password, nickname, phone } = this.form
            systemAdd({ username, password, nickname, phone })
              .then((res) => {
                this.$message.success({
                  message: '添加成功',
                  duration: 1000
                })
                this.getUserMessage()
              }).catch((res) => {
                this.$message.error({
                  message: '请稍后再试',
                  duration: 1000
                })
              })
          } else {
            const { username, password, nickname, phone } = this.form
            const userid = this.userid
            systemUpdate({ username, password, nickname, phone, userid })
              .then((res) => {
                this.$message.success({
                  message: '修改成功',
                  duration: 1000
                })
                this.form.password = ''
                this.form.againPassword = ''
                this.getUserMessage()
              }).catch((res) => {
                this.$message.error({
                  message: '请稍后再试',
                  duration: 1000
                })
              })
          }
        } else {
          return false
        }
      })
    },
    handleAdd() {
      this.form.username = ''
      this.form.nickname = ''
      this.form.phone = ''
      this.title = '添加后台管理用户'
      this.flag = true
      this.changeDialogVisible = true
    },
    handleDetail(scope) {
      const id = scope.row.id
      this.$router.push({
        path: `/safety/info/${id}`
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.safety-wrap {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  .form {
    display: flex;
    flex-wrap: wrap;
  }
  .switch-btn {
    margin-top: 20px;
    margin-bottom: 20px;
    margin-left: 20px;
  }
}
</style>
